

var table;
var editor; // use a global for the submit and return data rendering
var userTypeId = 0;
var user;
var communityId = "";
$(document).ready(function () {
    $.ajax({
        url: '/commis/api/user/currentUser',
        type: "GET",
        async: false,
        dataType: 'json',
        data: {},
        success: function (response) {
            if (response.status == 0) {
                console.log("用户存在");
                user = response.data;
                userTypeId = user.userTypeId;
                if (userTypeId == 4) {
                    communityId = user.communityId;
                }
                console.log(userTypeId);
            } else if (response.status == 1) {
                alert("登录用户已经过期，请重新登录");
                window.parent.location.href = "../../login.html";
            }
        }, error: function (msg) {
            alert("登录用户已经过期，请重新登录");
            window.parent.location.href = "../../login.html";
        }
    })


    $.ajax({
        url: '/commis/api/community/allCom',
        async: false,
        dataType: 'json',
        success: function (response) {
            console.log(response.length);
            for (var i = 0; i < response.length; i++) {
                $("#community").append("<option value='" + response[i].communityId + "'>" + response[i].communityName + "</option>");
            }


        }, error: function () {

        }
    });

    $('#registerTime').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true,
        todayBtn: true


    });
    var fields = [
        {
            label: "isOff:",
            name: "isOff",
            type: "hidden",
        }, {
            label: "submitNumber:",
            name: "submitNumber",
            type: "hidden",
        },
        {
            label: "isDelete:",
            name: "isDelete",
            type: "hidden",
        }, {
            label: "所属社区:",
            name: "communityId",
            type: "select"
        } , {
            label: "是否添加明细:",
            name: "detail",
            type: "radio",
            options: [
                {
                    label: "添加",
                    value: "1"
                }, {
                    label: "不添加",
                    value: "2"
                }
            ],
            def:"2"
        }, {
            label: "购置类型(办公用品、水费、电费等):",
            name: "workexpType"
        },{
            label: "物品名称:",
            name: "suppliesName"
        }, {
            label: "单价:",
            name: "unitCost"
        }, {
            label: "数量:",
            name: "count"
        }, {
            label: "金额:",
            name: "sum"
        }, {
            label: "支付方式:",
            name: "paymentMode"
        }, {
            label: "备注:",
            name: "comment"
        }]

    if (userTypeId == 4){
        fields = [
            {
                label: "isOff:",
                name: "isOff",
                type: "hidden",
            }, {
                label: "submitNumber:",
                name: "submitNumber",
                type: "hidden",
            },
            {
                label: "isDelete:",
                name: "isDelete",
                type: "hidden",
            }, {
                label: "购置类型:",
                name: "workexpType"
            } , {
                label: "是否添加明细:",
                name: "detail",
                type: "radio",
                options: [
                    {
                        label: "添加",
                        value: "1"
                    }, {
                        label: "不添加",
                        value: "2"
                    }
                ],
                def:"2"
            }, {
                label: "物品名称:",
                name: "suppliesName"
            }, {
                label: "单价:",
                name: "unitCost"
            }, {
                label: "数量:",
                name: "count"
            }, {
                label: "金额:",
                name: "sum"
            }, {
                label: "支付方式:",
                name: "paymentMode"
            }, {
                label: "备注:",
                name: "comment"
            }]
    }
    editor = new $.fn.dataTable.Editor({
        ajax: {
            create: {
                type: 'POST',
                url: '/commis/api/officeSupplies/create'
            },
            edit: {
                type: 'PUT',
                url: '/commis/api/officeSupplies/edit?id=_id_'
            },
            remove: {
                type: 'DELETE',
                url: '/commis/api/officeSupplies/remove?id=_id_'
            }
        },
        i18n: {
            create: {
                title: "申请办公经费",
                submit: "确定"
            },
            edit: {
                title: "修改记录",
                submit: "修改",
                confirm: "您确定要修改这 %d 条记录吗?"
            },
            remove: {
                title: "删除记录",
                submit: "删除",
                confirm: "您确定要删除这 %d 条记录吗?"
            }
        },
        idSrc: 'suppliesId',
        table: "#dataTable",
        fields: fields
    });
    editor.dependent( 'detail', function ( val ) {
        return val === '1' ?
            { show: ['suppliesName','unitCost','count'] } :
            { hide: ['suppliesName','unitCost','count'] };
    } );
    var buttons = [];
    var select = true;
    if (userTypeId == 1) {
        $("#communityDiv").show();
        select = true;
        buttons = [
            /*{extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'}*/
        ];
        console.log(buttons);


    } else if (userTypeId == 2) {
        $("#communityDiv").show();
        select = false;
        buttons = [
        ];

    } else if (userTypeId == 3||userTypeId == 6||userTypeId == 7||userTypeId == 8||userTypeId == 9) {
        $("#communityDiv").show();
        select = false;
        buttons = [];

    } else if (userTypeId == 4) {
        $("#communityDiv").hide();
        select = true;
        buttons = [
/*            {extend: "create", editor: editor, text: "申请", className: 'btn btn-primary'},*/
            {
                extend: "selectedSingle",
                text: "重新申请",
                className: 'btn btn-primary',
                action: function (e, dt, node, config) {

                    editor
                        .edit(table.row({selected: true}).index(), false);

                    var isOff = editor.get('isOff');
                    if (isOff != 2) {
                        alert("只有上级领导不同意的申请记录才能重新申请！");
                        return false;
                    }
                    var submitNumber = parseInt(editor.get('submitNumber')) + parseInt(1);

                    editor.set('submitNumber', submitNumber);
                    editor.submit();

                }
            }, {
                extend: "selectedSingle",
                text: "撤销申请",
                className: 'btn btn-primary',
                action: function (e, dt, node, config) {

                    editor
                        .edit(table.row({selected: true}).index(), false);

                    var isOff = editor.get('isOff');
                    if (isOff != 0 && isOff != 3) {
                        alert("已经有领导进行审批，不能撤销！");
                        return false;
                    }
                    editor.set('isDelete', '1');
                    editor.submit();

                }
            }
        ]
    }

    var table = $('#dataTable').DataTable({

        dom: "Bfrtip",
        ajax: "/commis/api/officeSupplies/pageDatatables",

        autoWidth: true,
        responsive: true,
        serverSide: true,
        processing: true,
        lengthChange: false,//是否允许用户改变表格每页显示的记录数
        ordering: false,//是否允许用户排序
        paging: true,//是否分页
        pagingType: "full_numbers",//除首页、上一页、下一页、末页四个按钮还有页数按钮
        searching: false,//是否开始本地搜索
        stateSave: false,//刷新时是否保存状态
        autoWidth: true,//自动计算宽度
        createdRow: function ( row, data, index ) {
            if ( data["isOff"] != 1) {
                // $('td', row).css("color","red");
                // $('td', row).css('backgroundColor','#FF0000')
                // $('td', row).eq(3).css('font-weight',"bold").css("color","red");
                $('td', row).css('backgroundColor', '#f8c4c4');
                // $('tr', row).css("color","red");
            }
        },
        language: {
            emptyTable: "没有数据",
            search: "搜索:",
            paginate: {
                first: "首页",
                previous: "上一页",
                next: "下一页",
                last: "尾页"

            },
            select: {
                rows: {
                    _: "选中 %d 行",
                    1: "选中 1 行"
                }/*,
                 columns: "选中 %d 列"*/
            },
            lengthMenu: "每页 _MENU_ 条记录",
            zeroRecords: "没有找到记录",
            info: "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )，共 _TOTAL_ 项",
            infoEmpty: "无记录",
            infoFiltered: "(从 _MAX_ 条记录过滤)"
        },
        columns: [
            {
                data: 'community.communityName', defaultContent: ""
            }, {
                data: 'suppliesId',
                render: function (data, type, row) {
                    return '<div class="operating_style Quick_operation"> <ul> <li class="submenu"><a name="officeSuppliesDetail.html?id=' + data + '" class="btn btn-primary btn-xs" title="办公经费申报详情">办公经费申报详情</a></li></ul> </div>';
                }
            }, {
                data: 'isOff',
                render: function (data, type, row) {
                    if(row.isOff==1){
                        return '<a href="api/officeSupplies/download/' + row.suppliesId + '" class="btn btn-primary btn-xs" >下载</a>';

                    }else{
                        return '<a onclick="alert('+"'未完成不能下载'"+')" class="btn btn-primary btn-xs" >下载</a>';

                    }
                }
            }, {
                data: 'user.realName', defaultContent: ""
            }, {
                data: 'registerTime', defaultContent: ""
            }, {
                data: 'workexpType', defaultContent: ""
            }, {
                data: 'sum', defaultContent: ""
            }, /*{
             data: 'liveAddr', defaultContent: ""
             },*/ {
                data: 'paymentMode', defaultContent: ""
            }, {
                data: 'comment', defaultContent: ""
            }, {
                data: 'isOff',
                render: function (data, type, row) {
                    if (1 == data) {
                        return "是";
                    } else {
                        return "否"
                    }
                }
            }], select: select,
        buttons: buttons

    });


    $('#search').on('click', function () {

        var url = "/commis/api/officeSupplies/pageDatatables?1=1"

        if (userTypeId != 4) {
            communityId = $('#community').val();

        }
        url = url + "&communityId=" + communityId;

        var params = [ "workexpType", "registerTime"];

        url = getUrl(url, params);


        table.ajax.url(url).load();
    });


    $('#userTable').on('change', 'input.editor-active', function () {
        editor
            .edit($(this).closest('tr'), false)
            .set('active', $(this).prop('checked') ? 1 : 0)
            .submit();
    });


})
//设置框架
$(function () {
    $("#page_style").frame({
        float: 'left',
        menu_nav: '.Quick_operation',
        color_btn: '.skin_select',
        Sellerber_menu: '.list_content',
        Sellerber_header: '.Sellerber_header',
    });
});
$("#iframe_box").niceScroll({
    cursorcolor: "#888888",
    cursoropacitymax: 1,
    touchbehavior: false,
    cursorwidth: "5px",
    cursorborder: "0",
    cursorborderradius: "5px"
});
/*********************/
require.config({
    paths: {
        echarts: './js/dist'
    }
});